/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.swirrel.installer;

import java.awt.Component;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import javax.swing.AbstractButton;
import javax.swing.JSlider;
import javax.swing.JSpinner;
import javax.swing.JTabbedPane;
import javax.swing.JViewport;
import javax.swing.event.ChangeListener;
import org.swirrel.annotation.StateChanged;
import org.swirrel.listener.SwirrelChangeListener;
import org.swirrel.util.SwirrelException;
import org.swirrel.util.MethodCall;

/**
 *
 * @author Gronau
 */
public class ChangeListenerInstaller extends AbstractListenerInstaller implements SwirrelListenerInstaller {

    public ChangeListenerInstaller() {
        super(Arrays.<Class<? extends Annotation>>asList(StateChanged.class),
                Arrays.<Class<?>>asList(AbstractButton.class,
                JTabbedPane.class, JSlider.class, JSpinner.class, JViewport.class));
    }

    public boolean isListenerAlreadySet(Object obj) {
        ChangeListener[] changeListeners = null;
        if (obj instanceof AbstractButton) {
            changeListeners = ((AbstractButton) obj).getChangeListeners();
        } else if (obj instanceof JTabbedPane) {
            changeListeners = ((JTabbedPane) obj).getChangeListeners();
        } else if (obj instanceof JSlider) {
            changeListeners = ((JSlider) obj).getChangeListeners();
        } else if (obj instanceof JSpinner) {
            changeListeners = ((JSpinner) obj).getChangeListeners();
        } else if (obj instanceof JViewport) {
            changeListeners = ((JViewport) obj).getChangeListeners();
        } else {
            throw new SwirrelException("Wrong class for ChangeListener: " + obj.getClass().getSimpleName());
        }
        for (ChangeListener al : changeListeners) {
            if (al instanceof SwirrelChangeListener) {
                return true;
            }
        }
        return false;
    }

    public void registerListener(Field field, Component comp, List<MethodCall> methodCalls) throws IllegalAccessException {
        Object obj = field.get(comp);
        ChangeListener al = new SwirrelChangeListener(methodCalls.get(0));
        if (obj instanceof AbstractButton) {
            ((AbstractButton) obj).addChangeListener(al);
        } else if (obj instanceof JTabbedPane) {
            ((JTabbedPane) obj).addChangeListener(al);
        } else if (obj instanceof JSlider) {
            ((JSlider) obj).addChangeListener(al);
        } else if (obj instanceof JSpinner) {
            ((JSpinner) obj).addChangeListener(al);
        } else if (obj instanceof JViewport) {
            ((JViewport) obj).addChangeListener(al);
        } else {
            throw new SwirrelException("Wrong class for ChangeListener: " + obj.getClass().getSimpleName());
        }
    }
}
